//
//  ATTrackHistoryViewController.m
//  ATGaode_demo
//
//  Created by Chengquan Ye on 2019/3/12.
//  Copyright © 2019年 Chengquan Ye. All rights reserved.
//

#import "ATTrackHistoryViewController.h"
#import <MAMapKit/MAMapKit.h>
#import "ATDrawTrackManager.h"
#import <SVProgressHUD.h>
#import "ATStepNumberManager.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define iPhone4S [UIScreen mainScreen].bounds.size.height == 480
#define iPhone5S [UIScreen mainScreen].bounds.size.height == 568
#define iPhone6S [UIScreen mainScreen].bounds.size.height == 667
#define iPhonePlus [UIScreen mainScreen].bounds.size.height == 736
#define iPad ([UIScreen mainScreen].bounds.size.height > 736 && [UIScreen mainScreen].bounds.size.height != 812)
#define iPhoneX ([UIScreen mainScreen].bounds.size.height == 812 && [UIScreen mainScreen].bounds.size.width == 375)
#define iPhoneXR [UIScreen mainScreen].bounds.size.height == 896
#define iPhoneXS_MAX [UIScreen mainScreen].bounds.size.height == 896
#define iPhoneX_series (iPhoneX || iPhoneXR || iPhoneXS_MAX)

#define NavHeight (iPhoneX_series ? 88 : 64)
#define TabBarHeight (iPhoneX_series ? 83 : 49)
#define SafeBottomHeight (iPhoneX_series ? 34 : 0)

static NSString * const sid = @"26335"; // 服务id

@interface ATTrackHistoryViewController () <MAMapViewDelegate, ATDrawTrackManagerDelegate, ATStepNumberManagerDelegate>

/** 绘制轨迹管理对象 */
@property (nonatomic, strong) ATDrawTrackManager *drawTrackManager;
/** <#name#> */
@property (nonatomic, strong) MAMapView *mapView;
/** 计步器管理 */
@property (nonatomic, strong) ATStepNumberManager *stepNumberManager;

/** 步数 */
@property (nonatomic, weak) UILabel *stepNumLbl;
/** 里程，计步器计算 */
@property (nonatomic, weak) UILabel *distanceLbl;
/** 里程，高德计算 */
@property (nonatomic, weak) UILabel *distanceOtherLbl;

/** <#name#> */
@property (nonatomic, assign) NSInteger pageIndex;

@end

@implementation ATTrackHistoryViewController

- (ATDrawTrackManager *)drawTrackManager
{
    if (!_drawTrackManager) {
        _drawTrackManager = [ATDrawTrackManager manager];
        _drawTrackManager.gatherInterval = 2;
        _drawTrackManager.packInterval = 10;
    }
    return _drawTrackManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"查询轨迹";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.pageIndex = 1;
    
    
    [self setupUI];
    
    [self.drawTrackManager setupTrackManager:sid];
    self.drawTrackManager.delegate = self;
    
    self.stepNumberManager = [ATStepNumberManager manager];
    self.stepNumberManager.delegate = self;
    
    if (self.startDate && self.endDate) {
        [self.stepNumberManager stepNumberWithStartDate:self.startDate endDate:self.endDate];
    }
    
    [self queryTracks];
    
    [self queryDistance];
    
    [self queryTracksAndHistory];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}


- (void)setupUI
{
    self.mapView = [[MAMapView alloc] init];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    self.mapView.frame = self.view.bounds;
    self.mapView.delegate = self;
    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    // 不显示罗盘
    self.mapView.showsCompass = NO;
    
    // 不显示比例尺
    self.mapView.showsScale = NO;
    
    //是否自定义用户位置精度圈
    self.mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    
    MACircle *circle = [MACircle circleWithCenterCoordinate:self.mapView.userLocation.coordinate radius:0];
    [self.mapView addOverlay:circle];
    
    //    self.mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    //    self.mapView.distanceFilter = 5; // kCLDistanceFilterNone
    
    self.mapView.pausesLocationUpdatesAutomatically = NO;
    
    [self.mapView setZoomLevel:19];
    [self.view addSubview:self.mapView];
    
    // 修改地图样式
    NSString *path = [NSString stringWithFormat:@"%@/style.data", [NSBundle mainBundle].bundlePath];
    NSData *styleData = [NSData dataWithContentsOfFile:path];
    MAMapCustomStyleOptions *styleOption = [[MAMapCustomStyleOptions alloc] init];
    styleOption.styleData = styleData;
    [self.mapView setCustomMapStyleOptions:styleOption];
    [self.mapView setCustomMapStyleEnabled:YES];
    
    UILabel *stepNumLbl = [[UILabel alloc] init];
    stepNumLbl.frame = CGRectMake(10, SCREEN_HEIGHT - 10 * 2 - 30 * 3, 150, 30);
//    stepNumLbl.textAlignment = NSTextAlignmentRight;
    stepNumLbl.textColor = [UIColor whiteColor];
    stepNumLbl.backgroundColor = [UIColor blackColor];
    stepNumLbl.text = @"步数: 0米";
    [self.view addSubview:stepNumLbl];
    self.stepNumLbl = stepNumLbl;
    
    UILabel *distanceLbl = [[UILabel alloc] init];
    distanceLbl.frame = CGRectMake(10, SCREEN_HEIGHT - 10 - 30 * 2, 150, 30);
//    distanceLbl.textAlignment = NSTextAlignmentRight;
    distanceLbl.textColor = [UIColor redColor];
    distanceLbl.textColor = [UIColor whiteColor];
    distanceLbl.backgroundColor = [UIColor blackColor];
    distanceLbl.text = @"计步: 0米";
    [self.view addSubview:distanceLbl];
    self.distanceLbl = distanceLbl;
    
    UILabel *distanceOtherLbl = [[UILabel alloc] init];
    distanceOtherLbl.frame = CGRectMake(10, SCREEN_HEIGHT - 30, 150, 30);
//    distanceOtherLbl.textAlignment = NSTextAlignmentRight;
    distanceOtherLbl.textColor = [UIColor redColor];
    distanceOtherLbl.textColor = [UIColor whiteColor];
    distanceOtherLbl.backgroundColor = [UIColor blackColor];
    distanceOtherLbl.text = @"高德: 0米";
    [self.view addSubview:distanceOtherLbl];
    self.distanceOtherLbl = distanceOtherLbl;
}


- (void)queryDistance
{
//    serviceID:26335, terminalID:28257710, trackID:900, startDate:Tue Mar 12 11:00:08 2019, endDate:Tue Mar 12 11:13:12 2019
    NSLog(@"serviceID:%@, terminalID:%@, trackID:%@, startDate:%@, endDate:%@", self.drawTrackManager.serviceID, self.terminalID, self.trackID, self.startDate, self.endDate);
    AMapTrackQueryTrackDistanceRequest *request = [[AMapTrackQueryTrackDistanceRequest alloc] init];
    request.serviceID = self.drawTrackManager.serviceID; // @"26335"; //
    request.terminalID = self.terminalID; // @"28257710"; //
    request.trackID = self.trackID; // @"680"; //
    request.startTime = [self.startDate timeIntervalSince1970] * 1000; // [[[NSDate date] dateByAddingTimeInterval:-60 * 60] timeIntervalSince1970] * 1000; //
    request.endTime = [self.endDate timeIntervalSince1970] * 1000;
//    request.correctionMode = @"driving"; // [[NSDate date] timeIntervalSince1970] * 1000; //
    //    request.pageSize = self.pageSize; // 每页返回点的数量，最大不超过1000
    //    request.pageIndex = self.pageIndex;
    
    [self.drawTrackManager queryTrackDistance:request];
}

- (void)queryTracks
{
    NSLog(@"serviceID:%@, terminalID:%@, trackID:%@, startDate:%@, endDate:%@", self.drawTrackManager.serviceID, self.terminalID, self.trackID, self.startDate, self.endDate);
    AMapTrackQueryTrackInfoRequest *request = [[AMapTrackQueryTrackInfoRequest alloc] init];
    request.serviceID = self.drawTrackManager.serviceID; // @"26335"; //
    request.terminalID = self.terminalID; // @"28257710"; //
    request.trackID = self.trackID; // @"680"; //
    request.startTime = [self.startDate timeIntervalSince1970] * 1000; // [[[NSDate date] dateByAddingTimeInterval:-60 * 60] timeIntervalSince1970] * 1000; //
    request.endTime = [self.endDate timeIntervalSince1970] * 1000; // [[NSDate date] timeIntervalSince1970] * 1000; //
//    request.correctionMode = @"driving";
    //    request.pageSize = self.pageSize; // 每页返回点的数量，最大不超过1000
    //    request.pageIndex = self.pageIndex;
    
    [self.drawTrackManager queryTrackInfo:request];
}

- (void)queryTracksAndHistory
{
    NSLog(@"serviceID:%@, terminalID:%@, trackID:%@, startDate:%@, endDate:%@", self.drawTrackManager.serviceID, self.terminalID, self.trackID, self.startDate, self.endDate);
    AMapTrackQueryTrackHistoryAndDistanceRequest *request = [[AMapTrackQueryTrackHistoryAndDistanceRequest alloc] init];
    request.serviceID = self.drawTrackManager.serviceID; // @"26335"; //
    request.terminalID = self.terminalID; // @"28257710"; //
    request.startTime = [self.startDate timeIntervalSince1970] * 1000; // [[[NSDate date] dateByAddingTimeInterval:-60 * 60] timeIntervalSince1970] * 1000; //
    request.endTime = [self.endDate timeIntervalSince1970] * 1000; // [[NSDate date] timeIntervalSince1970] * 1000; //
    //    request.correctionMode = @"driving";
    //    request.pageSize = self.pageSize; // 每页返回点的数量，最大不超过1000
    request.pageIndex = self.pageIndex;
    
    [self.drawTrackManager queryTrackHistoryAndDistance:request];
}

#pragma mark - ATDrawTrackManagerDelegate
- (void)queryTrackDistanceDone:(AMapTrackQueryTrackDistanceRequest *)request response:(AMapTrackQueryTrackDistanceResponse *)response
{
    self.distanceOtherLbl.text = [NSString stringWithFormat:@"高德: %zd米", response.distance];
}

- (void)queryTrackInfoDone:(AMapTrackQueryTrackInfoRequest *)request response:(AMapTrackQueryTrackInfoResponse *)response
{
    NSLog(@"onQueryTrackInfoDone%@", response.formattedDescription);
    [self.mapView removeOverlays:[self.mapView overlays]];
    for (AMapTrackBasicTrack *track in response.tracks) {
        if ([[track points] count] > 0) {
            [self showPolylineWithTrackPoints:[track points]];
        }
    }
    [self.mapView showOverlays:self.mapView.overlays animated:NO];
}

- (void)queryTrackHistoryAndDistanceDone:(AMapTrackQueryTrackHistoryAndDistanceRequest *)request response:(AMapTrackQueryTrackHistoryAndDistanceResponse *)response
{
    NSLog(@"queryTrackHistoryAndDistanceDone%@", response.formattedDescription);
    if ([[response points] count] > 0) {
        //        [self.mapView removeOverlays:[self.mapView overlays]];
        
        [self showPolylineWithTrackPoints:[response points]];
        [self.mapView showOverlays:self.mapView.overlays animated:NO];
        
        if (response.points.count == self.drawTrackManager.pageSize) {
            self.pageIndex++;
            
            [self queryTracksAndHistory];
        }
    }
    [self.mapView showOverlays:self.mapView.overlays animated:NO];
}

#pragma mark - Helper
- (void)showPolylineWithTrackPoints:(NSArray<AMapTrackPoint *> *)points {
    int pointCount = (int)[points count];
    
    CLLocationCoordinate2D *allCoordinates = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i < pointCount; i++) {
        allCoordinates[i].latitude = [[points objectAtIndex:i] coordinate].latitude;
        allCoordinates[i].longitude = [[points objectAtIndex:i] coordinate].longitude;
    }
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:allCoordinates count:pointCount];
    [self.mapView addOverlay:polyline];
    
    if (allCoordinates) {
        free(allCoordinates);
        allCoordinates = NULL;
    }
}

#pragma mark - MAMapViewDelegate
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        
        MAPolylineRenderer * polylineRenderer = [[MAPolylineRenderer alloc] initWithOverlay:overlay];
        polylineRenderer.lineWidth = 5.f;
        polylineRenderer.strokeColor = [UIColor greenColor];
        polylineRenderer.lineJoinType = kMALineJoinRound;
        polylineRenderer.lineCapType = kMALineCapRound;
        
        return polylineRenderer;
    }
    
    if ([overlay isKindOfClass:[MACircle class]]) {
        
    }
    
    return nil;
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
//    NSLog(@"纬度: %f--------经度: %f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
}

#pragma mark - ATStepNumberManagerDelegate
- (void)stepNumber:(NSDictionary *)dict
{
    self.stepNumLbl.text = [NSString stringWithFormat:@"步数: %@步", dict[@"numberOfSteps"]];
    self.distanceLbl.text = [NSString stringWithFormat:@"计步: %zd米", [dict[@"distance"] integerValue]];
}

@end
